



import { useState, useEffect } from 'react';
import { Button, Table, Form, Tooltip } from 'antd';
import type { ColumnsType } from 'antd/es/table';
import { observer } from '@formily/react';
import { TextWidget, getMessage } from '@inbiz/react';
import {
    useGetComponentLangListByCodeEffect,
    useGetSystemMessageEffect,
    useEditLangItemEffect,
} from '@inbiz/render';
import { postMessage, copyToClipboard, InbizIcon, getFormatKey, getLangNameByCode } from '@inbiz/utils';
import { uid } from '@inbiz/shared';
import Pagination from '@inbiz/basic/Pagination';
import type { DataType, LangType } from '../index'
import { EditableCell } from '../index'
import styles from './index.less';

export interface IComponentsProps {
    langs: LangType[];
    pageOutId: string;
    code: string;
    searchValue: string
    isGlobalQuery: boolean
}

let pageSize = 20;
let pageIndex = 1;


export const EditLangTable = observer((props: IComponentsProps) => {
    const langs = props.langs;
    const pageOutId = props.pageOutId;
    const [dateState, $dateState] = useState([] as any);
    const [columnsState, $columnsState] = useState<ColumnsType<DataType>>([]);
    const [selectedRowKeys, setSelectedRowKeys] = useState<React.Key[]>([]);
    const [editingKey, setEditingKey] = useState('');
    const isEditing = (record: DataType) => record.key === editingKey;
    const [formTable] = Form.useForm();
    const businessLangList = useGetComponentLangListByCodeEffect();
    const getSystem = useGetSystemMessageEffect();
    const editLangItem = useEditLangItemEffect(true);
    const onSelectChange = (newSelectedRowKeys: React.Key[]) => {
        setSelectedRowKeys(newSelectedRowKeys);
    };

    const rowSelection = {
        selectedRowKeys,
        onChange: onSelectChange,
    };

    // 获取表格列表
    const getBusinessLangList = ({
        pageSize,
        index,
        code,
        pageOutId,
        searchValue
    }: any) => {
        businessLangList(
            {
                pageSize: pageSize,
                index: index,
                componentCode: code,
                pageOutId: pageOutId,
                likeContext: searchValue,
                isGlobalQuery: props.isGlobalQuery
            },
            (res: any) => {
                $dateState(res);
            },
        );
    };

    const openColumnEdit = (
        data = {
            key: `i18n-${uid(8)}`,
        },
    ) => {
        if (Object.keys(data).length < 2) {
            langs.forEach((item: LangType) => {
                data[item.Code] = '';
            });
            const topItem = dateState[0];
            if (topItem) {
                if (!topItem.person) {
                    dateState.shift();
                }
            }
            const allNewGroups: any = [data, ...dateState];
            allNewGroups.total = dateState.total + 1;
            $dateState(allNewGroups);
        }

        formTable.setFieldsValue(data);
        setEditingKey(data.key);
    };

    const closeColumnModal = () => {
        formTable.setFieldsValue({
            key: uid(16),
        });
        langs.forEach((item: LangType) => {
            formTable.setFieldsValue({
                [item.Code]: '',
            });
        });
        setEditingKey('');
    };

    const submitModal = (record: DataType) => {
        formTable
            .validateFields()
            .then((values) => {
                const allLang = Object.values(values);
                const isNull = allLang.some((item: any) => {
                    return item.trim() == '';
                });
                if (isNull) {
                    const newObj = {};
                    langs.forEach((item: LangType) => {
                        if (values[item.Code].trim() == '') {
                            newObj[item.Code] = '';
                        } else {
                            newObj[item.Code] = values[item.Code];
                        }
                    });
                    formTable.setFieldsValue({
                        key: record.key,
                        ...newObj,
                    });
                    return;
                }

                editLangItem(
                    {
                        key: record.key,
                        siteType: record.siteType,
                        kindItems: langs?.map((item: LangType) => ({
                            kindCode: item.Code,
                            langText: values[item.Code],
                        })),
                    },
                    () => {
                        getBusinessLangList({
                            index: pageIndex,
                            pageSize: pageSize,
                            pageOutId: pageOutId,
                            code: props.code,
                            searchValue: props.searchValue
                        });
                        getSystem('zh-cn');

                        // VsCode环境下Message通讯
                        postMessage({
                            module: 'languageDesign',
                            event: 'edit',
                            data: {
                                key: record.key,
                            },
                        });
                    },
                );
                closeColumnModal();
            })
            .catch((err) => { });
    };

    const resetList = () => {
        dateState.shift();
        const newList: any = [...dateState];
        newList.total = dateState.total - 1;
        $dateState(newList);
    };

    useEffect(() => {
        let columns: ColumnsType<DataType> | any = [
            {
                title: '依赖名称',
                dataIndex: 'componentName',
                key: 'componentName',
                width: 100,
                editable: true,
                ellipsis: true,
                render: (val: string) => {
                    const name = getLangNameByCode(val);
                    return <span title={name}>{name}</span>;
                },
            },
            {
                title: '唯一标识',
                dataIndex: 'key',
                key: 'key',
                width: 200,
                editable: true,
                ellipsis: true,
                render: (val: string) => {
                    return <span title={val}>{getFormatKey(val)}</span>;
                },
            }
        ];

        // 根据语种展示多语言表格列数
        langs?.map((item: LangType, i) => {
            columns.push({
                title: item.Name,
                dataIndex: item.Code,
                key: item.Id,
                width: 120,
                editable: true,
                ellipsis: true,
                render: (val: string) => {
                    return <span title={val}>{val}</span>;
                },
            });
        });

        // 拼接操作栏
        columns = columns.concat([
            {
                title: getMessage('global.operate'),
                key: 'action',
                fixed: 'right',
                width: 120,
                render: (_: any, record: LangType | any) => {
                    const editable = isEditing(record);
                    return !editable ? (
                        <div className={styles.operate}>
                            <Tooltip placement="bottom" title={`唯一标识: ${record.key} (点击复制)`}>
                                <InbizIcon
                                    type={'icon-inbiz_other-copy'}
                                    onClick={() => {
                                        copyToClipboard(record.key);
                                    }}
                                />
                            </Tooltip>
                            <InbizIcon
                                type={'icon-bianji'}
                                onClick={() => {
                                    openColumnEdit(record);
                                }}
                            />
                        </div>
                    ) : (
                        <div className={styles.operate}>
                            <Button
                                type="link"
                                style={{ maxWidth: 42, padding: 0 }}
                                onClick={() => {
                                    submitModal(record);
                                }}
                            >
                                <TextWidget>global.save</TextWidget>
                            </Button>
                            <Button
                                style={{ maxWidth: 42, padding: 0 }}
                                type="link"
                                onClick={() => {
                                    setEditingKey('');
                                    if (newLang.type == 'new') {
                                        resetList();
                                    }
                                }}
                            >
                                <TextWidget>global.cancel</TextWidget>
                            </Button>
                        </div>
                    );
                },
            },
        ]);

        //转化赋值可编辑属性
        columns = columns.map((col: any) => {
            if (!col.editable) {
                return col;
            }
            return {
                ...col,
                onCell: (record: DataType) => ({
                    record,
                    inputType: 'text',
                    dataIndex: col.dataIndex,
                    title: col.title,
                    editing: isEditing(record),
                }),
            };
        });

        $columnsState(columns);
    }, [langs, editingKey]);

    useEffect(() => {
        getBusinessLangList({
            index: 1,
            pageSize: 20,
            pageOutId: pageOutId,
            code: props.code,
            searchValue: props.searchValue
        });
    }, [pageOutId, props.code, props.searchValue])

    return (
        <div className={styles.wrapModal}>
            <Form form={formTable} component={false}>
                <Table
                    components={{
                        body: {
                            cell: EditableCell,
                        },
                    }}
                    bordered
                    rowSelection={rowSelection}
                    columns={columnsState}
                    dataSource={dateState}
                    rowClassName="editable-row"
                    size={'small'}
                    style={{
                        minHeight: 330,
                    }}
                    pagination={false}
                    scroll={{ x: 646, y: 288 }}
                />
            </Form>
            <Pagination
                size='small'
                className={styles.pagination}
                options={[10, 20, 30, 50, 100]}
                total={dateState.total || 1}
                current={pageIndex}
                pageSize={pageSize}
                onChange={(page: any) => {
                    pageSize = page.pageSize;
                    pageIndex = page.current;
                    getBusinessLangList({
                        index: pageIndex,
                        pageSize: pageSize,
                        pageOutId: pageOutId,
                        code: props.code,
                        searchValue: props.searchValue
                    });
                }}
            />
        </div>
    );
});
